import { Component, OnInit, ViewChild } from '@angular/core';
import { NzModalRef, NzMessageService } from 'ng-zorro-antd';
import { _HttpClient, SettingsService } from '@delon/theme';
import { SFSchema, SFUISchema } from '@delon/form';
import { UserService } from '../../../../service/user/user.service';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { deepCopy } from '@delon/util';
import { ServiceResult } from '@core/constant';
import { CommService } from '../../../../service/comm/comm.service';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'client-user-edit',
  templateUrl: './edit.component.html',
  styles: [`:host ::ng-deep .ant-form-item { 
        margin-bottom: 12px;
    }`]
})
export class ClientEditComponent implements OnInit {
  record: any = {};
  userInfo = null;
  parentId;
  brands = [];
  listOfSelectedValue = [];
  parentObj = null;
  loading = false;
  constructor(
    private trans: TranslateService,
    private comm: CommService,
    private setting: SettingsService,
    private msg: NzMessageService,
    private user: UserService,
    private modal: NzModalRef,
    public msgSrv: NzMessageService,
    public http: _HttpClient,
  ) {}

  ngOnInit(): void {        
    if (this.record.child_id) {
      this.parentId = this.record.parent_id;         
      this.user.info(this.record.child_id).pipe(
        catchError(err => { return of(err); })
      ).subscribe(ret=>{
        if (ret.status === 200) {
            const data = ret.data;
            this.record = data;

            this.userInfo = JSON.parse(this.record.userId);
            if (typeof this.userInfo === 'object' && this.userInfo) {
                this.record.userId = this.userInfo.id;                
            } 
        } else {
            this.msg.error(ret.message);
        }
      });      
    } 
    this.user.info(this.parentId).pipe(
        catchError(err => { return of(err)})
    ).subscribe(ret => {
        if (ret.status === 200) {
            this.parentObj = ret.data;
        }
    })
    
    this.loadBrands();
  }


  loadBrands() {
    let mybrands = [];
    this.brands = [];    
    this.comm.getBrand().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.status === 200) {            
        // 如果是管理员，则获取该2级用户上级的品牌. 否则获取当前用户的品牌
        if (this.setting.user.isManager) {
            this.user.info(this.parentId || this.record.parent_id).pipe(catchError(err => {return of(err)})).subscribe(userret => {
                if (userret['status'] === 200) {
                    if (userret['data'].brand) {
                        mybrands = userret['data'].brand.split(',');
                    }
                }            
                // 过滤品牌
                for (const row of ret['data']['rows']) {
                    if (mybrands.indexOf(row.value) > -1) {
                      this.brands.push({ text: (row.labelEnUs).toUpperCase(), value: row.value });
                      this.listOfSelectedValue.push(row.value);
                    }
                } 
            })
        } else {
            if (this.setting.user.brand) {
                mybrands = this.setting.user.brand.split(',');
            }
            // 过滤品牌
            for (const row of ret['data']['rows']) {
                if (mybrands.indexOf(row.value) > -1) {
                  this.brands.push({ text: (row.labelEnUs).toUpperCase(), value: row.value });
                  this.listOfSelectedValue.push(row.value);
                }
            } 
        }                            
      }
    })
  }
  
  save() {      
    let userForm = deepCopy(this.record);        
    if (!userForm.name) {
        this.msg.warning('This name is required');
        return;
    }
    
    if (!userForm.username) {
        this.msg.warning('This account is required');
        return;
    }

    if ("admin" === userForm.username) {
        this.msg.warning('不能以"admin"作为账户名');
        return;
    }

    if (!userForm.id && !userForm.password) {
        this.msg.warning('This password is required');
        return;
    }
    if (!userForm.id && (userForm.password.length < 4 || userForm.password.length > 16)) {
        this.msg.warning('Password must have at least 4 characters');
        return;
    }
    let lang = this.trans.currentLang || this.trans.defaultLang;
    if (this.listOfSelectedValue.length === 0) {
        this.msg.warning(lang === 'en' ? 'This brand is required' : '请选择品牌');
        return;
    }
    userForm.level = "SECOND";
    userForm.account = userForm.username;
    userForm.parentId = this.parentId;   
    
    userForm.currency = this.parentObj.currency;
    userForm.siteCode = this.parentObj.siteCode;

    userForm.brand = this.listOfSelectedValue.toString();
    if (userForm.id) {    
        this.loading = true;    
        this.user.modify(userForm).pipe(
            catchError(err => {
                return of(err)
            })
        ).subscribe(ret => {
            this.loading = false;
            if (ret.status == 200) {
                this.msg.success('Successful');
                this.close();
            } else {
                this.msg.error(ret.message);
            }
        })
    } else {
        this.loading = true;
        this.user.addSecond(userForm).pipe(
            catchError(err => {
                return of(err);
            })
        ).subscribe(ret => {
            this.loading = false;
            if (ret.status == 200) {
                this.msg.success('Successful');
                this.close();
            } else {
                this.msg.error(ret.message);
            }
        })
    }
  }

  close() {
    this.modal.close(true);
    this.modal.destroy();
  }
}
